//
//  RentsViewController.swift
//  test
//
//  Created by george on 12/23/15.
//  Copyright © 2015 test. All rights reserved.
//

import UIKit
import CoreData

class RentsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

	var table: UITableView = UITableView()
	var rents: [Rent] {
		get {
			let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
			let request = NSFetchRequest(entityName: "Rent")
			do {
				return try delegate.mainQueueMOC.executeFetchRequest(request) as! [Rent]
			} catch {
				fatalError("WRONG")
			}
		}
	}

	override func viewDidLoad() {
		super.viewDidLoad()
		view.backgroundColor = UIColor.whiteColor()

		table.dataSource = self
		table.delegate = self
		table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
		view.addSubview(table)

		let new = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "new")
		self.navigationItem.rightBarButtonItem = new
	}

	override func viewWillAppear(animated: Bool) {
		super.viewWillAppear(animated)
		table.reloadData()
	}

	override func viewWillLayoutSubviews() {
		super.viewWillLayoutSubviews()

		table.translatesAutoresizingMaskIntoConstraints = false
		view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[table]|", options: .AlignAllBaseline, metrics: nil, views: ["table":table]))
		view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[table]|", options: .AlignAllBaseline, metrics: nil, views: ["table":table]))
	}

	func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return self.rents.count
	}

	func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
		let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)

		cell.textLabel?.text = self.rents[indexPath.row].title
		cell.detailTextLabel?.text = self.rents[indexPath.row].content
		return cell
	}

	func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
		let hvc = HouseViewController()
		hvc.hidesBottomBarWhenPushed = true
		hvc.house = self.rents[indexPath.row].house
		self.navigationController?.showViewController(hvc, sender: self)
	}

	func new() {
		let newVC = NewEntryViewController()
		newVC.title = "New Rent"
		newVC.task = NewEntryTask.Rent
		let cancel = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "dismiss")
		newVC.navigationItem.rightBarButtonItem = cancel
		let nvc = UINavigationController(rootViewController: newVC)
		self.navigationController?.showDetailViewController(nvc, sender: self)
	}

	func dismiss() {
		self.dismissViewControllerAnimated(true, completion: nil)
	}

}
